package exchange

import (
	"global/core"
	"time"
	"github.com/parnurzeal/gorequest"
	"global/constants"
	"github.com/ngaut/log"
	"global/libs/structs"
	"encoding/json"
	"srv/cmc/cap"
)

type ListAllExchange struct {
	Ctx 		*core.Context
	Client 		*gorequest.SuperAgent
	Key 		string
	IntervalC 	*time.Ticker
}

func NewListAllExchange() cap.InterfaceCmc {
	return &ListAllExchange{
		// 3 分钟更新
		IntervalC: 		time.NewTicker(time.Minute * 3),
	}
}

func (c *ListAllExchange) Init(ctx *core.Context) cap.InterfaceCmc {
	c.Ctx = ctx
	c.Client = gorequest.New()
	c.Key = c.Ctx.AccountConfig()
	return c
}

func (c *ListAllExchange) Run() error {
	go func() {
		c.handler()
		for t := range c.IntervalC.C {
			_ = t
			go c.handler()
		}
	}()
	return nil
}

func (c *ListAllExchange) handler() {
	log.Infof("start handler 24h volume for exchanges.")
	start := time.Now()
	_, body, errs := c.Client.
		Get(core.GetCmcUrl(c.Ctx.IsDebug(), constants.CmcListLatestAllExchangesUrl)).
		Set("X-CMC_PRO_API_KEY", c.Key).
		Query(map[string]interface{}{
			"limit": 5000,
			"convert": "USD,CNY,BTC",
		}).
		End()
	if len(errs) != 0 {
		log.Errorf("Error: list all latest exchagnes info error, msg: %s", errs[0].Error())
		return
	}

	type CmcData struct {
		Status 			structs.CmcStatus 				`json:"status"`
		Data 			[]structs.ExchangeLatestData 	`json:"data"`
	}

	var parsedCmcData CmcData
	err := json.Unmarshal([]byte(body), &parsedCmcData)
	if err != nil {
		log.Errorf("Error: %s", err.Error())
		return
	}

	if parsedCmcData.Status.ErrorCode != 0 {
		log.Errorf("Error: %s", parsedCmcData.Status.ErrorMessage)
		return
	}

	conn := c.Ctx.GetBaseRedis().Get()
	defer conn.Close()
	err = core.SaveExchangeVolume24h(conn, parsedCmcData.Data)
	if err != nil {
		log.Infof("Error: %s", err.Error())
	}
	log.Infof("handler 24h volume success, exchanges: %d, take time: %s", len(parsedCmcData.Data), time.Since(start))
}